<?php

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name)
            return $name;
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }

}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++)
            $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }

}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }

}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }

}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $url = preg_match("/^https?:\/\/(.*)/i", $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
            if (is_bool($domain)) {
                $public = \think\Config::get('view_replace_str.__PUBLIC__');
                $url = rtrim($public, '/') . $url;
                if (!preg_match("/^(http:\/\/|https:\/\/)/i", $url)) {
                    $url = request()->domain() . $url;
                }
            } else {
                $url = $domain . $url;
            }
        }
        return $url;
    }

}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === FALSE) {
                return FALSE;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return TRUE;
        } elseif (!is_file($file) OR ($fp = @fopen($file, 'ab')) === FALSE) {
            return FALSE;
        }
        fclose($fp);
        return TRUE;
    }

}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname))
            return false;
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }

}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }

}

if (!function_exists('mb_ucfirst')) {

    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }

}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields)
            return $items;
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }

}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, TRUE);
        }
    }

}

/*ep_public_common*/
// 应用公共文件
error_reporting(E_ALL & ~E_NOTICE);
/**
 * 通用API接口数据输出
 * @param string $msg 提示信息
 * @param int $status 状态码 1、成功，2、失败
 * @param [] $data  数据
 * @param int $httpCode http状态码
 * @return array
 */
function renderJson($msg = '', $status = 0, $data = [])
{
    header('Content-type: application/json');
    $resultData = [];
    if ($data) {
        if (is_assoc($data)){
            $resultData = $data;
        } else {
            $resultData['list'] = $data;
        }
    } else {
        $resultData = new StdClass();
    }

    echo json_encode([
        "msg" => $msg,
        "status"  => $status,
        "data"    => $resultData,
    ]);

    exit();
}

/**
 * 判断是否关联数组 true:关联数组
 * @param $arr
 * @return bool
 */
function is_assoc($arr) {
    if (is_array($arr) ) {
        return array_keys($arr) !== range(0, count($arr) - 1);
    } else {
        return true;
    }
}

if (!function_exists('check_mobile')) {
    /**
     * 手机号码正则验证
     * @Author   chenjianghui
     * @DateTime 2018-04-17T11:14:44+0800
     * @param    [type]                   $mobile 手机号码
     * @return   [type]                           \think\Response
     */
    function check_mobile($mobile)
    {
        $preg_phone = '/^1[3456789]\d{9}$/ims';
        if (preg_match($preg_phone, $mobile)) {
            return true;
        } else {
            return false;
        }
    }
}


if (!function_exists('check_email')) {
    /**
     * 邮箱正则验证
     * @Author   chenjianghui
     * @DateTime 2018-04-17T11:14:44+0800
     * @param    [type]                   $email 手机号码
     * @return   [type]                          [description]
     */
    function check_email($email)
    {
        $preg_email = '/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@([a-zA-Z0-9]+[-.])+([a-z]{2,5})$/ims';
        if (preg_match($preg_email, $email)) {
            return true;
        } else {
            return false;
        }
    }
}

function curl($url, $postFields = null)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //https 请求
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }

    if (is_array($postFields) && 0 < count($postFields)) {
        $postBodyString = "";
        $postMultipart  = false;
        foreach ($postFields as $k => $v) {
            if ("@" != substr($v, 0, 1)) //判断是不是文件上传
            {
                $postBodyString .= "$k=" . urlencode($v) . "&";
            } else //文件上传用multipart/form-data，否则用www-form-urlencoded
            {
                $postMultipart = true;
            }
        }
        unset($k, $v);
        curl_setopt($ch, CURLOPT_POST, true);
        if ($postMultipart) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
        }
    }
    $reponse = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception(curl_error($ch), 0);
    } else {
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (200 !== $httpStatusCode) {
            throw new Exception($reponse, $httpStatusCode);
        }
    }
    curl_close($ch);
    return $reponse;
}


function is_weixin(){

    if ( strpos($_SERVER['HTTP_USER_AGENT'],

            'MicroMessenger') !== false ) {

        return true;

    }

    return false;

}

function numTrmb($num){
    $d = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
    $e = array('元', '拾', '佰', '仟', '万', '拾万', '佰万', '仟万', '亿', '拾亿', '佰亿', '仟亿');
    $p = array('分', '角');
    $zheng = "整";
    $final = array();
    $inwan = 0;//是否有万
    $inyi = 0;//是否有亿
    $len = 0;//小数点后的长度
    $y = 0;
    $num = round($num, 2);//精确到分
    if(strlen($num) > 15){
        return "金额太大";
        die();
    }
    if($c = strpos($num, '.')){//有小数点,$c为小数点前有几位
        $len=strlen($num)-strpos($num,'.')-1;//小数点后有几位数
    }else{//无小数点
        $c = strlen($num);
        $zheng = '整';
    }
    for($i = 0; $i < $c; $i++){
        $bit_num = substr($num, $i, 1);
        if ($bit_num != 0 || substr($num, $i + 1, 1) != 0) {
            @$low = $low . $d[$bit_num];
        }
        if ($bit_num || $i == $c - 1) {
            @$low = $low . $e[$c - $i - 1];
        }
    }
    if($len!=1){
        for ($j = $len; $j >= 1; $j--) {
            $point_num = substr($num, strlen($num) - $j, 1);
            @$low = $low . $d[$point_num] . $p[$j - 1];
        }
    }else{
        $point_num = substr($num, strlen($num) - $len, 1);
        $low=$low.$d[$point_num].$p[$len];
    }
    $chinses = str_split($low, 3);//字符串转化为数组
    for ($x = count($chinses) - 1; $x >= 0; $x--) {
        if ($inwan == 0 && $chinses[$x] == $e[4]) {//过滤重复的万
            $final[$y++] = $chinses[$x];
            $inwan = 1;
        }
        if ($inyi == 0 && $chinses[$x] == $e[8]) {//过滤重复的亿
            $final[$y++] = $chinses[$x];
            $inyi = 1;
            $inwan = 0;
        }
        if ($chinses[$x] != $e[4] && $chinses[$x] !== $e[8]) {
            $final[$y++] = $chinses[$x];
        }
    }
    $newstr = (array_reverse($final));
    $nstr = join($newstr);
    if((substr($num, -2, 1) == '0') && (substr($num, -1) <> 0)){
        $nstr = substr($nstr, 0, (strlen($nstr) -6)).'零'. substr($nstr, -6, 6);
    }
    $nstr=(strpos($nstr,'零角')) ? substr_replace($nstr,"",strpos($nstr,'零角'),6) : $nstr;
    return $nstr = (substr($nstr,-3,3)=='元') ? $nstr . $zheng : $nstr;
}


/*生成唯一订单编号*/
/*
 * 1.date("Ymd")：这个很容易理解，是在最前方拼接一个当前年月日组成的数字。
   2.uniqid()：此函数获取一个带前缀、基于当前时间微秒数的唯一ID。
   3.substr(uniqid(), 7, 13)：由于uniqid()函数生成的结果前面7位很久才会发生变化，所以有或者没有对于我们没有多少影响，所以我们截取后面经常发生变化的几位。
   4.str_split(substr(uniqid(), 7, 13),1)：我们将刚刚生成的字符串进行分割放到数组里面，str_split()第二个参数是每个数组元素的长度。
   5.array_map('ord', str_split(substr(uniqid(), 7, 13),1)))：其中array_map()函数作用为：函数返回用户自定义函数作用后的数组，意思就是ord是函数ord(),而后面第二个参数是ord()函数的参数。可以这么理解ord(str_split(substr(uniqid(),7, 13), 1)))。然后ord()是干啥的，ord()函数php内置函数：返回字符串的首个字符的 ASCII值，意思就是把第二个参数生成的数组每个元素全部转换为数字，因为刚刚我们截取的字符串中含有字母，不适合订单号。
   6.implode()：很简单了，把刚刚那个转换成数字的数字在拼接成为一个数字。
   7.由于刚刚生成的随机数可能会长短不一（原因就是，每个字符转换为ASCII值可能不一样，有些是2位，有些可能是一位），所以我们同意截取0-8
   8.然后加上刚刚的日期数字，现在就凑成了一个等长的高大上的订单号了~
 * */
function get_only_order_no(){
    return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
